package com.jianyun.jyzs.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.LeaveMenuBean;
import com.jianyun.jyzs.utils.DataFactory;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.RightTopDialog;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author 杨仕俊
 * @description 所有的web标签 H5
 * Created by yangshijun on 2018/9/6.
 */

public class HtmlActivity extends AppCompatActivity {


    @BindView(R.id.imgbtn_custom_nav_back)
    ImageButton imgbtnCustomNavBack;
    @BindView(R.id.imgbtn_custom_nav_finish)
    ImageButton imgbtnCustomNavFinish;
    @BindView(R.id.tv_custom_nav_title)
    TextView tvCustomNavTitle;
    @BindView(R.id.tv_custom_nav_sub_title)
    TextView tvCustomNavSubTitle;
    @BindView(R.id.ll_custom_nav_title)
    LinearLayout llCustomNavTitle;
    @BindView(R.id.tv_custom_nav_option)
    TextView tvCustomNavOption;
    @BindView(R.id.imgbtn_custom_nav_option)
    ImageButton imgbtnCustomNavOption;
    @BindView(R.id.rl_actionbar)
    RelativeLayout rlActionbar;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;

    private String mPrevUrl = "";
    private ArrayList<LeaveMenuBean> leaveMenuBeans;
    private ArrayList<LeaveMenuBean.HtmlJsInitBean> htmlJsInitBean;
    private RightTopDialog rightTopDialog;
    private static final int FILE_CHOOSER_RESULT_CODE = 123;
    private boolean askedgalleryPermission = false;
    private int galleryPermissionReqCode = 202;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    //文字类
                    imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
                    tvCustomNavOption.setText(leaveMenuBeans.get(0).getText());
                    tvCustomNavOption.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    if (htmlJsInitBean != null) {
                        String isNeed = htmlJsInitBean.get(0).getIsNeed();
                        //展示右上角
                        if ("true".equals(isNeed)) {
                            //imgbtnCustomNavOption.setVisibility(View.VISIBLE);
                        } else {
                            //imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
                        }
                        String initFlag = htmlJsInitBean.get(0).getInitFlag();
                        String initFn = htmlJsInitBean.get(0).getInitFn();
                        if ("true".equals(initFlag)) {
                            //执行初始化方法
                            String jsFn = "javascript:" + initFn;
                            webView.loadUrl(jsFn);
                        }
                    }
                    break;
                case 3:
                    //图片类
                    //需要设置图片
                    tvCustomNavOption.setVisibility(View.INVISIBLE);
                    imgbtnCustomNavOption.setVisibility(View.VISIBLE);
                    imgbtnCustomNavOption.setImageResource(R.drawable.wc_edit);
                    break;
                case 4:
                    //弹出菜单类
                    tvCustomNavOption.setVisibility(View.INVISIBLE);
                    imgbtnCustomNavOption.setVisibility(View.VISIBLE);
                    break;
                case 5:
                    //全部隐藏
                    Log.i("test", "隐藏");
                    tvCustomNavOption.setVisibility(View.INVISIBLE);
                    imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
                    break;
                default:
                    break;
            }

        }
    };
    private ValueCallback<Uri[]> uploadMessageAboveL;


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rce_activity_webhtml);
        ButterKnife.bind(this);
        initData();
        initView();
        initRight();
    }

    private void initRight() {
        //右上角弹窗选择
        rightTopDialog = new RightTopDialog(this, new RightTopDialog.OnListViewLinsenter() {
            @Override
            public void onclickPosition(int i) {
                if (leaveMenuBeans != null || leaveMenuBeans.size() > 0) {
                    String fnName = leaveMenuBeans.get(i).getFnName();
                    String js = "javascript:" + fnName;
                    webView.loadUrl(js);
                }
            }
        }, leaveMenuBeans);


    }

    private void initData() {

        String url = getIntent().getStringExtra("url");

        String tag = getIntent().getStringExtra("tag");

        if (!TextUtils.isEmpty(tag) && "请假".equals(tag)) {
            imgbtnCustomNavOption.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(url)) {
            if (url.startsWith("http") || url.startsWith("https")) {
                mPrevUrl = url;
            } else {
                mPrevUrl = LoginCache.getInstance().getLoginCache().getErpRootUrl() + url;
            }
        }
        String urlUserHelper = getIntent().getStringExtra("urlUserHelper");
        if (!TextUtils.isEmpty(urlUserHelper)) {
            mPrevUrl = urlUserHelper;
        }
        String replaceAll = getIntent().getStringExtra("replaceAll");
        if (!TextUtils.isEmpty(replaceAll)) {
            mPrevUrl = replaceAll;
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initView() {
        webView.setVerticalScrollbarOverlay(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT > 11) {
            webView.getSettings().setDisplayZoomControls(false);
        }
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        //设置可以访问文件
        webView.getSettings().setAllowFileAccess(true);
        webView.setWebViewClient(new OAWebViewClient());
        webView.setWebChromeClient(new OAWebChromeClient());
        webView.setDownloadListener(new MyWebViewDownLoadListener());
        webView.addJavascriptInterface(new JavaScriptObject(), "control");//传递对象进行交互
        Log.i("test", "html中：" + mPrevUrl);
        webView.loadUrl(mPrevUrl);
        imgbtnCustomNavOption.setVisibility(View.INVISIBLE);

    }

    @OnClick({R.id.imgbtn_custom_nav_back, R.id.imgbtn_custom_nav_finish, R.id.imgbtn_custom_nav_option, R.id.tv_custom_nav_option})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgbtn_custom_nav_back:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                break;
            case R.id.imgbtn_custom_nav_finish:
                finish();
                break;
            case R.id.imgbtn_custom_nav_option:
                //右上角
                String type = leaveMenuBeans.get(0).getType();
                if ("icon".equals(type)) {
                    String fnName = leaveMenuBeans.get(0).getFnName();
                    String js = "javascript:" + fnName;
                    webView.loadUrl(js);
                } else if ("menu".equals(type)) {
                    rightTopDialog.showPopupWindow(imgbtnCustomNavOption);
                }
                break;
            case R.id.tv_custom_nav_option:
                //右上角
                String fnName = leaveMenuBeans.get(0).getFnName();
                if (fnName!=null){
                    String js = "javascript:" + fnName;
                    webView.loadUrl(js);
                }
                break;
        }
    }


    public class JavaScriptObject {
        @JavascriptInterface
        public void setMenuJson(String json) {
            if (json != null && !TextUtils.isEmpty(json)) {
                Message message = new Message();
                leaveMenuBeans = DataFactory.jsonToArrayList(json, LeaveMenuBean.class);
                if (leaveMenuBeans != null) {
                    String type = leaveMenuBeans.get(0).getType();
                    switch (type) {
                        case "text":
                            message.arg1 = 1;
                            break;
                        case "icon":
                            message.arg1 = 3;
                            break;
                        case "menu":
                            message.arg1 = 4;
                            rightTopDialog.setLeaveBane(leaveMenuBeans);
                            break;
                    }
                }
                mHandler.sendMessage(message);
                Log.i("test", "解析：" + leaveMenuBeans.toString());

            }

        }

        @JavascriptInterface
        public void setInitJson(String initJson) {
            if (initJson != null && !TextUtils.isEmpty(initJson)) {
                htmlJsInitBean = DataFactory.jsonToArrayList(initJson, LeaveMenuBean.HtmlJsInitBean.class);
                Message message = new Message();
                message.arg1 = 2;
                mHandler.sendMessage(message);
                Log.i("test", "初始化解析：" + htmlJsInitBean.toString());
            }

        }

        @JavascriptInterface
        public void hideView() {
            Message message = new Message();
            message.arg1 = 5;
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void showTest(String test){
            ToastUtil.showToast(HtmlActivity.this, test);
        }


    }


    public class OAWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("test", "url:" + url);
            if (mPrevUrl != null) {
                if (!mPrevUrl.equals(url)) {
                    if (!(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://"))) {
                        Intent intent = new Intent("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(url);
                        intent.setData(content_url);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        try {
                            startActivity(intent);
                        } catch (Exception e) {
                            Log.e("err", "not apps install for this intent =" + e.toString());
                            e.printStackTrace();
                        }
                        return true;
                    }
                    mPrevUrl = url;
                    webView.loadUrl(url);
                    return true;
                } else {
                    return false;
                }
            } else {
                mPrevUrl = url;
                webView.loadUrl(url);
                return true;
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onPageFinished(WebView view, String url) {

            // 换成下面该方法即可
            webView.evaluateJavascript("javascript:getPhoneMenu()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.i("test", "菜单的：" + value);
                    //字符串替换
                    String s = value.replaceAll("\\\\", "");
                    //此处为 js 返回的结果
                    if ("null".equals(value)) {
                        imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
                        tvCustomNavOption.setVisibility(View.INVISIBLE);
                    } else {
                        //imgbtnCustomNavOption.setVisibility(View.VISIBLE);
                    }
                }
            });

            // 换成下面该方法即可
            webView.evaluateJavascript("javascript:phoneInitJson", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.i("test", "初始化的：" + value);
                    //字符串替换
                    String s = value.replaceAll("\\\\", "");
                    //此处为 js 返回的结果
//                    if ("null".equals(value)) {
//                        imgbtnCustomNavOption.setVisibility(View.INVISIBLE);
//                    } else {
//                        imgbtnCustomNavOption.setVisibility(View.VISIBLE);
//                    }
                }
            });
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.INVISIBLE);

        }
    }


    private class OAWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (tvCustomNavTitle != null && !TextUtils.isEmpty(title)) {
                tvCustomNavTitle.setText(title);

            }
        }


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);

        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }

    private void openImageChooserActivity() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == FILE_CHOOSER_RESULT_CODE) {
                if (null == uploadMessageAboveL) return;
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        try {
            if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
                return;
            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (intent != null) {
                    String dataString = intent.getDataString();
                    ClipData clipData = intent.getClipData();
                    if (clipData != null) {
                        results = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            results[i] = item.getUri();
                        }
                    }
                    if (dataString != null)
                        results = new Uri[]{Uri.parse(dataString)};
                }
            }
            uploadMessageAboveL.onReceiveValue(results);
            uploadMessageAboveL = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * webview点击下载
     */
    class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            showFile(url);
        }

    }

    public void showFile(String url) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //有权限
            //其他手机 下载 打开
            startActivity((new Intent(this, ShowFileActivity.class))
                    .putExtra("type", -1)
                    .putExtra("id", -1)
                    .putExtra("folderID", "workFlow")
                    .putExtra("remotepath", url));
        } else if (!askedgalleryPermission) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    galleryPermissionReqCode);
            askedgalleryPermission = true;
        }
    }
}

